#!/usr/bin/env python2
# -*- mode:python; coding:utf-8 -*-

"""
A todo manager
"""

__author__ = "valens_a, lecalv_g"
__version__ = "todo 0.03"
__license__ = "LGPL"
__maintainer__ = "valens_a, lecalv_g"
__email__ = "valens_a@epitech.eu, lecalv_g@epitech.eu"
__status__ = "Production"

# ------------------------------------------

TODO_FILENAME = '.todo'

cBLK = "\x1b[0;30m"
cRED = "\x1b[0;31m"
cGRN = "\x1b[0;32m"
cBRN = "\x1b[0;33m"
cBLU = "\x1b[0;34m"
cMGN = "\x1b[0;35m"
cCYA = "\x1b[0;36m"
cNOR = "\x1b[0;37m"
cGRA = "\x1b[1;30m"
cLRD = "\x1b[1;31m"
cLGN = "\x1b[1;32m"
cYEL = "\x1b[1;33m"
cLBL = "\x1b[1;34m"
cPIN = "\x1b[1;35m"
cLCY = "\x1b[1;36m"
cBRI = "\x1b[1;37m"
cRST = "\x1b[0m"

cYELS = "\x1b[1;9;33m"
cLOR = "\x1b[1m\x1b[38;5;214m"
cVIOLET = "\x1b[1m\x1b[38;5;220m"
cLWH = "\x1b[1m\x1b[38;5;246m"
cORA = "\x1b[38;5;214m"

cBOLD = "\x1b[1m"

# ------------------------------------------

import os,sys
import csv
import argparse
import re

# ------------------------------------------

def enum(**enums):
    return type('Enum', (), enums)

TaskType = enum(TODO='1', DONE='2')

# ------------------------------------------

class CsvTaskParser:
    def __init__(self, filename):
        self.filename = filename

    def arrayToCsv(self, arrays):
        out = csv.writer(open(self.filename,"w+"), delimiter=',', quoting=csv.QUOTE_ALL)
        for array in arrays:
            out.writerow(array)

    def csvToArray(self):
        reader = csv.reader(open(self.filename, "rb"), delimiter=',')
        todo = []
        done = []
        names = []
        for data in reader:
            if data[0] == TaskType.TODO:
                todo.append(data)
            elif data[0] == TaskType.DONE:
                done.append(data)
            names = todo + done
        return names

# ------------------------------------------

class TaskManager:
    def __init__(self):
        self.taskNum = 1
        self.csvParser = CsvTaskParser(TODO_FILENAME)

    def addTask(self, args):
        if os.path.isfile(TODO_FILENAME) == False:
            todoList = []
        else:
            todoList = self.csvParser.csvToArray()
        taskArray = ['1', args.add, os.environ['USER'], '']
        todoList.append(taskArray)
        self.csvParser.arrayToCsv(todoList)
        self.showTasks(args)
        print '\n%sTask added%s' % (cLGN, cRST)

    def showTasks(self, args):
        if os.path.isfile(TODO_FILENAME) == False :
            if not args.silent:
                print '\n%sNo task, you can drink a coffee!%s' % (cLGN, cRST)
            return
        print 'Task list:'
        todoList = self.csvParser.csvToArray()
        self.__printTodoList(args, todoList)
        if args.file:
            fileTodoList = self.__getTasksInFile(args)
            self.__printTodoList(args, fileTodoList)

    def __printTodoList(self, args, todoList):
        for task in todoList:
            output = '%s\t[%i]%s - ' % (cLBL, self.taskNum, cRST)
            if task[0] == TaskType.TODO:
                output += '%sTODO:%s %s' % (cLWH, cRST, task[1])
            elif task[0] == TaskType.DONE:
                output += '%sDONE:%s %s' % (cLGN, cRST, task[1])
            if args.verbose == True:
                output += ' %screated by %s%s' % (cLWH, cRST, task[2])
                if task[0] == TaskType.DONE:
                    output += ' %sfinished by %s%s' % (cLWH, cRST, task[3])
            print output
            # print '%s\t[%i]%s - %sTODO:%s %s' % (cLBL, i, cRST, cLWH, cRST, task)
            self.taskNum += 1

    def deleteTask(self, args):
        n = args.delete
        todoList = self.csvParser.csvToArray()
        if n - 1 >= 0 and n - 1 < len(todoList):
            todoList.pop(n - 1)
            if len(todoList) == 0:
                os.remove(TODO_FILENAME)
            else:
                self.csvParser.arrayToCsv(todoList)
            print '\n%sTask [%d] deleted%s' % (cLGN, n, cRST)
            self.showTasks(args)
        else:
            print '%sIndex error%s' % (cLRD, cRST)

    def finishTask(self, args):
        n = args.finished
        todoList = self.csvParser.csvToArray()
        if n - 1 >= 0 and n - 1 < len(todoList):
            if todoList[n - 1][0] == TaskType.DONE:
                print '%sTask is already DONE%s' % (cLRD, cRST)
                self.showTasks(args)
                return
            todoList[n - 1][0] = TaskType.DONE
            todoList[n - 1][3] = os.environ['USER']
            self.csvParser.arrayToCsv(todoList)
            print '\n%sTask [%d] is now DONE%s' % (cLGN, n, cRST)
            self.showTasks(args)
        else:
            print '%sIndex error%s' % (cLRD, cRST)

    def __parseTodoLine(self, line):
        line = line[line.find('TODO'):]
        line = re.sub('TODO[: ]*', '', line)
        line = re.sub('\*/$', '', line)
        line = line.strip()
        return line

    def __getTasksInFile(self, args):
        todoList = []
        i = 0
        print 'In File %s:' % args.file
        for line in open(args.file):
            if "TODO" in line:
                line = self.__parseTodoLine(line)
                taskArray = [TaskType.TODO, line, '', '']
                todoList.append(taskArray)
            i += 1
        return todoList

# ------------------------------------------

def main():
    parser = argparse.ArgumentParser(description='Manage TODO tasks on a directory')
    parser.add_argument('-a', '--add', type=str, help='to add task')
    parser.add_argument('-d', '--delete', type=int, help='to delete task')
    parser.add_argument('-f', '--finished', type=int, help='change task n to status DONE')
    parser.add_argument('--file', type=str, help='show todos in file')
    # Can be use if you call todo each time you do a cd command
    parser.add_argument('-s', '--silent', action='store_true', help='do not show "no task" when no task')
    parser.add_argument('-v', '--verbose', action='store_true', help='show creator/finisher')
    args = parser.parse_args()
    
    manager = TaskManager()

    if args.add:
        manager.addTask(args)
    elif args.delete:
        manager.deleteTask(args)
    elif args.finished:
        manager.finishTask(args)
    else:
        manager.showTasks(args)

    # if args.file:
    #     manager.showTasksInFile(args)

if __name__ == "__main__":
    main()

# ------------------------------------------
